package cn.enjoy.socket.udp.multicast;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.nio.charset.StandardCharsets;

/**
 * @author K
 * @date 2024-06-04 20:27
 * 组播发送者
 * <p>
 * 广播实现是最简单的，在单播的基础上把发送端的IP改为255.255.255.255，这时候则会对当前局域网内的所有ip发送数据
 **/
public class UDPMulticastSend {

    public static void main(String[] args) {

        MulticastSocket multicastSocket = null;
        try {
            //创建组播Socket
            multicastSocket = new MulticastSocket();

            //将当前本机添加到224.0.0.1的这一组中（发送数据到这一组）
            // IP地址范围为224.0.0.0（特殊不可用）至239.255.255.255(包含)
            InetAddress groupId = InetAddress.getByName("224.0.0.1");
            multicastSocket.joinGroup(groupId);

            //把要发送的消息打包
            byte[] bytes = "一个简单下消息：\r\n您好朋友".getBytes(StandardCharsets.UTF_8);
            DatagramPacket datagramPacket = new DatagramPacket(bytes, 0, bytes.length, groupId, 10086);

            //发送消息
            multicastSocket.send(datagramPacket);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (multicastSocket != null) {
                //关闭
                multicastSocket.close();
            }
        }
    }
}